package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class SearchController {

    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(@RequestParam Map<String ,String> searchMap, Model model) throws Exception {

        //字符集处理(解决中文乱码问题)
        searchMap= WebUtil.convertCharsetToUTF8(searchMap);

        //url处理
        StringBuffer url=new StringBuffer("/search.do?");
        for(String key:searchMap.keySet()){
            url.append("&"+key+"="+searchMap.get(key) );
        }
        model.addAttribute("url",url);

        //searchMap的预加载
        Map map = skuSearchService.search(searchMap);
        model.addAttribute("searchMap",map);

        //分页页码的预加载
        Integer pageNo = Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        //排序的预加载

        //页面传递给后端 两个参数      sort：排序字段   sortOrder：排序规则（升序/降序）
        if (searchMap.get("sort")==null){//排序字段
            searchMap.put("sort","");
        }
        if (searchMap.get("sortOrder")==null){//排序规则
            searchMap.put("sortOrder","DESC");
        }

        return "search";
    }

}
